<template>
  <div v-on="$listeners">
    <slot name="dragContent" :dragEvent="dragEvent"></slot>
  </div>
</template>

<script lang="ts">
import { Vue, Component, PropSync } from "vue-property-decorator";
@Component({
  props: {
    dragItem: {
      type: Object,
    },
  },
})
export default class Drag extends Vue {
  @PropSync("dragData", { type: Array }) syncedDragData!: object[];
  @PropSync("enterItem", { type: Object }) syncedEnterItem!: object;
  oldData: object | null = null; // 开始排序时按住的旧数据
  get propDragItem() {
    return this.$props.dragItem;
  }
  dragEvent = {
    dragstart: this.dragstart,
    dragenter: this.dragenter,
    dragend: this.dragend,
    dragover: this.dragover,
  };
  // 拖拽开始
  dragstart() {
    this.oldData = this.propDragItem;
  }

  // 记录移动过程中信息
  dragenter() {
    this.syncedEnterItem = this.propDragItem;
    const e = window.event;
    e && e.preventDefault();
  }

  // 拖拽最终操作
  dragend() {
    if (this.oldData !== this.syncedEnterItem) {
      let oldIndex = this.syncedDragData.indexOf(this.oldData as object);
      let newIndex = this.syncedDragData.indexOf(this.syncedEnterItem);
      let newItems = [...this.syncedDragData];
      // 删除老的节点
      newItems.splice(oldIndex, 1);
      // 在列表中目标位置增加新的节点
      newItems.splice(newIndex, 0, this.oldData as object);
      this.syncedDragData = [...newItems];
    }
  }

  // 拖动事件（主要是为了拖动时鼠标光标不变为禁止）
  dragover() {
    const e = window.event;
    e && e.preventDefault();
  }
}
</script>

<style lang="scss" scoped>
@import "@/components/JobSheet/Drag/Drag.scss";
</style>
